package com.jn.zhinongbao.adapter.adapter;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.example.supportingagriculturaltreasures.MerchantOrderActivity;
import com.example.supportingagriculturaltreasures.R;
import com.example.supportingagriculturaltreasures.bean.Order;

import java.io.File;
import java.util.List;

public class MerchantOrderAdapter extends RecyclerView.Adapter<MerchantOrderAdapter.OrderViewHolder> {

    private List<Order> orderList;
    private OnOrderActionListener listener;

    public interface OnOrderActionListener {
        void onOrderClick(Order order);
        void onOrderLongClick(Order order);
    }

    public MerchantOrderAdapter(List<Order> orderList, OnOrderActionListener listener) {
        this.orderList = orderList;
        this.listener = listener;
    }

    public void updateOrders(List<Order> newOrders) {
        this.orderList = newOrders;
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public OrderViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_merchant_order, parent, false);
        return new OrderViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull OrderViewHolder holder, int position) {
        Order order = orderList.get(position);
        holder.bind(order);
    }

    @Override
    public int getItemCount() {
        return orderList.size();
    }

    public class OrderViewHolder extends RecyclerView.ViewHolder {
        private TextView tvOrderId;
        private ImageView ivProductImage;
        private TextView tvProductName;
        private TextView tvProductPrice;
        private TextView tvQuantity;
        private TextView tvTotalAmount;
        private TextView tvOrderStatus;
        private TextView tvCreateTime;
        private TextView tvShippingAddress;
        private TextView tvContactPhone;

        public OrderViewHolder(@NonNull View itemView) {
            super(itemView);
            tvOrderId = itemView.findViewById(R.id.tv_order_id);
            ivProductImage = itemView.findViewById(R.id.iv_product_image);
            tvProductName = itemView.findViewById(R.id.tv_product_name);
            tvProductPrice = itemView.findViewById(R.id.tv_product_price);
            tvQuantity = itemView.findViewById(R.id.tv_quantity);
            tvTotalAmount = itemView.findViewById(R.id.tv_total_amount);
            tvOrderStatus = itemView.findViewById(R.id.tv_order_status);
            tvCreateTime = itemView.findViewById(R.id.tv_create_time);
            tvShippingAddress = itemView.findViewById(R.id.tv_shipping_address);
            tvContactPhone = itemView.findViewById(R.id.tv_contact_phone);
        }

        public void bind(Order order) {
            tvOrderId.setText("订单号: " + order.getId());
            tvProductName.setText(order.getProductName());
            tvProductPrice.setText("¥" + String.format("%.2f", order.getProductPrice()));
            tvQuantity.setText("x" + order.getQuantity());
            tvTotalAmount.setText("¥" + String.format("%.2f", order.getTotalAmount()));
            
            // 设置订单状态和颜色
            String statusText = MerchantOrderActivity.getStatusText(order.getStatus());
            int statusColor = MerchantOrderActivity.getStatusColor(order.getStatus());
            tvOrderStatus.setText(statusText);
            tvOrderStatus.setTextColor(statusColor);
            
            tvCreateTime.setText("下单时间: " + order.getCreateTime());
            tvShippingAddress.setText("收货地址: " + order.getShippingAddress());
            tvContactPhone.setText("联系电话: " + order.getContactPhone());
            
            // 加载商品图片
            loadProductImage(order.getProductImageUrl());
            
            // 设置点击事件
            itemView.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onOrderClick(order);
                }
            });

            // 设置长按事件
            itemView.setOnLongClickListener(v -> {
                if (listener != null) {
                    listener.onOrderLongClick(order);
                }
                return true;
            });
        }
        
        private void loadProductImage(String imageUrl) {
            if (imageUrl == null || imageUrl.isEmpty()) {
                ivProductImage.setImageResource(R.drawable.ic_launcher_foreground);
                return;
            }
            
            Context context = itemView.getContext();
            
            // 判断是文件路径还是content URI
            Object imageSource;
            if (imageUrl.startsWith("/")) {
                // 文件路径
                File imageFile = new File(imageUrl);
                if (imageFile.exists()) {
                    imageSource = imageFile;
                } else {
                    // 文件不存在，显示默认图片
                    ivProductImage.setImageResource(R.drawable.ic_launcher_foreground);
                    return;
                }
            } else if (imageUrl.startsWith("content://")) {
                // content URI
                imageSource = Uri.parse(imageUrl);
            } else {
                // 其他情况，直接使用字符串
                imageSource = imageUrl;
            }
            
            // 使用Glide加载图片
            Glide.with(context)
                    .load(imageSource)
                    .placeholder(R.drawable.ic_launcher_foreground)
                    .error(R.drawable.ic_launcher_foreground)
                    .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                    .centerCrop()
                    .override(200, 200)
                    .listener(new RequestListener<Drawable>() {
                        @Override
                        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                            if (e != null) {
                                e.printStackTrace();
                            }
                            return false;
                        }

                        @Override
                        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                            return false;
                        }
                    })
                    .into(ivProductImage);
        }
    }
} 